local skynet = require "skynet"
local service_class = require "service_class"

local table_insert = table.insert
local table_unpack = table.unpack

local worker_mgr = class("worker_mgr",service_class)

function worker_mgr:ctor() 
	self.data_workers = {}
end

function worker_mgr:reload() 
end

function worker_mgr:init(conf)
	local worker_name = conf.worker_name
	local worker_num = conf.worker_num
	local redis_conf = {
		redis_host = conf.redis_host,
		redis_port = conf.redis_port,
		redis_db   = conf.redis_db,
		redis_auth = conf.redis_auth,
		
		pre_alloc = conf.pre_alloc,
		max_cache_connection_num = conf.max_cache_connection_num,

		dirty_queue_db = conf.dirty_queue_db,
		dirty_queue_key = conf.dirty_queue_key,
	}

	for i = 1,worker_num do
		local worker = skynet.newservice('common_service',worker_name)
		skynet.call(worker,'lua','open',redis_conf)
		table_insert(self.data_workers,worker)
	end
end

function worker_mgr:start(conf)
	self:init(conf)

	print('start.... worker num is ',conf.worker_num)
	skynet.dispatch('lua',function(_,_,cmd,id, ...)
		local i = 1
		print("worker_mgr start11111",cmd,id,...)
		if id and type(id) == 'number' then
			i = id % #self.data_workers + 1
		end
		local r = {skynet.call(self.data_workers[i],'lua',cmd,id,...)}
		if #r > 0 then
			return skynet.retpack(table_unpack(r))
		end
	end)

	return true
end

return worker_mgr